package com.youdianstar.app.common.util.dialog

import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.os.CountDownTimer
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.TextView
import com.youdianstar.app.common.PHOTO_ALBUM
import com.youdianstar.app.common.PHOTO_CAMERA
import com.youdianstar.app.common.R
import com.youdianstar.app.common.util.ScreenUtil
import com.youdianstar.app.common.util.StrUtil

/**
 * File: DialogUtil
 * Author: 82149 Create: 2021/9/22 17:57
 * Changes (from 2021/9/22)
 * --------------------------------------------------
 * description:
 * ---------------------------------------------------
 *
 */
open class DialogUtil : DialogHelper.OnDialogCancelListener{
    override fun onCancelListener(dialog: DialogInterface?) {
       cleanDialog()
    }
    interface OnCountFinishListener {
        fun countFinish()
    }

    var helper: DialogHelper? = null
    var dialog: Dialog? = null

//    private var loadingDialog : Dialog? = null
    private var frameLoadDialog: FrameLoadDialog?=null

    companion object {
        val instance by lazy { DialogUtil() }
    }

    init {
        helper = DialogHelper(this)
    }

    fun hideInputKeyboard(context: Context, v: EditText) {
        val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(v.windowToken, 0)
        v.clearFocus()
    }

    /**
     * 清除Dialog
     */
    fun cleanDialog() {
        dialog?.dismiss()
        dialog = null
    }

    /**
     * 显示Dialog
     */
    fun showDialog() {
        dialog?.show()
    }


    /**
     * 关闭loading
     */
    fun dismissLoading() {
//        loadingDialog?.dismiss()
//        loadingDialog = null
        frameLoadDialog?.dismissLoading()
        frameLoadDialog = null
    }

    /**
     * show Loading
     * 不要让DialogUtil 绑定Context;
     *
     * @param context view
     */
    fun showLoading(context: Context) {
        dismissLoading()
//        loadingDialog = helper?.getLoadingDialog(context,  true)
//        loadingDialog?.setCanceledOnTouchOutside(false)
        frameLoadDialog = FrameLoadDialog(context,R.style.LoadingDialogStyle)
        try {
//            loadingDialog?.show()
            frameLoadDialog?.showLoading()
        } catch (ignored: Exception) {
            ignored.printStackTrace()
        }
    }

    private var mCountTimer: CountDownTimer?=null
    private var autoDialog : Dialog?=null

    /**
     * 显示二次确认弹框
     * --支持自动关闭
     *
     * @param context
     * @param msg     data
     * @param count 倒计时 5s
     */
    fun showAutoCheckDialog(context: Activity,
                            title: String, msg: String,
                            confirmAction: (() -> Unit) = { },
                            confirmTx: String? = null,
                            isShowBtn: Boolean = true,
                            isAutoCancel: Boolean = false,
                            count:Long = 5000,
                            listener:OnCountFinishListener?=null
    ): Dialog {
        dismissAutoDialog()
        val rootView: View = LayoutInflater.from(context).inflate(R.layout.layout_dialog_confirm, null)
        autoDialog = helper?.createBaseDialog(context, R.style.AlertDialogStyle, false, rootView)
        val tvTitle = rootView.findViewById<TextView>(R.id.tv_title)
        val tvMsg = rootView.findViewById<TextView>(R.id.tv_msg)
        val tvConfirm = rootView.findViewById<TextView>(R.id.tv_confirm)

        if (!StrUtil.isEmpty(title)) {
            tvTitle.visibility = View.VISIBLE
            tvTitle.text = title
        } else
            tvTitle.visibility = View.GONE
        tvMsg.text = msg

        tvConfirm.visibility = if (isShowBtn) View.VISIBLE else View.GONE
        confirmTx?.let {
            tvConfirm.text = it
        }
        tvConfirm.setOnClickListener {
            dialog?.dismiss()
            confirmAction()
        }

        helper?.adjustSizeGravity(autoDialog, (ScreenUtil.getScreenSize(context).x * 0.86).toInt(), 0, Gravity.CENTER)
        autoDialog?.show()
        if (isAutoCancel){
            listener?.let { countListener->
                startCountDownTimer(null,"",count,countListener)
            }
        }
        return autoDialog!!
    }

    fun dismissAutoDialog(){
        if (null != autoDialog && autoDialog?.isShowing == true)
            autoDialog?.dismiss()
        autoDialog = null
        stopCountDownTimer()
    }

    /**
     * 倒计时 显示
     * @param tvConfirm 文本确认控件
     * @param formatPart 其他提示文本
     */
    private fun startCountDownTimer(tvConfirm: TextView?=null, formatPart: String = "",
        count: Long,
        listener: OnCountFinishListener
    ) {
        stopCountDownTimer()
        mCountTimer = object : CountDownTimer(count, 1000L) {
            override fun onTick(millisUntilFinished: Long) {
                if (null != tvConfirm && !StrUtil.isEmpty(formatPart)) {
                    val countText = String.format("%s(%ds)", formatPart, millisUntilFinished / 1000)
                    tvConfirm.text = countText
                }
            }

            override fun onFinish() {
                autoDialog?.dismiss()
                listener.countFinish()
            }
        }
        mCountTimer?.start()
    }

    private fun stopCountDownTimer(){
        mCountTimer?.cancel()
    }

    /**
     * 显示二次确认
     *
     * @param context
     * @param msg     data
     */
    fun showNotifyDialog(context: Activity,
                          title: String, msg: String,
                          leftAction: (() -> Unit) = { },
                          rightAction: (() -> Unit) = { },
                          left: String? = null,
                          isShowLeft: Boolean = true,
                          right: String? = null,
                          isShowRight: Boolean = true
    ): Dialog {
        cleanDialog()
        val rootView: View = LayoutInflater.from(context).inflate(R.layout.layout_dialog_notify, null)
        dialog = helper?.createBaseDialog(context, R.style.AlertDialogStyle, false, rootView)
        val tvTitle = rootView.findViewById<TextView>(R.id.tv_title)
        val tvMsg = rootView.findViewById<TextView>(R.id.tx_content)
        val tvLeft = rootView.findViewById<TextView>(R.id.tv_Left)
        val tvRight = rootView.findViewById<TextView>(R.id.tv_Right)
        val tvVertical = rootView.findViewById<TextView>(R.id.tv_vertical)

        tvLeft.setOnClickListener {
            dialog?.dismiss()
            try {
                leftAction()
            } catch (_: Exception) {
            }
        }
        tvRight.setOnClickListener {
            dialog?.dismiss()
            rightAction()
        }

        if (!StrUtil.isEmpty(title)) {
            tvTitle.visibility = View.VISIBLE
            tvTitle.text = title
        } else
            tvTitle.visibility = View.GONE
        tvMsg.text = msg
        tvVertical.visibility = if (isShowLeft && isShowRight) View.VISIBLE else View.GONE
        tvLeft.visibility = if (isShowLeft) View.VISIBLE else View.GONE
        tvRight.visibility = if (isShowRight) View.VISIBLE else View.GONE
        left?.let {
            tvLeft.text = it
        }
        right?.let {
            tvRight.text = it
        }
        helper?.adjustSizeGravity(dialog, (ScreenUtil.getScreenSize(context).x * 0.86).toInt(), 0, Gravity.CENTER)
        showDialog()
        return dialog!!
    }


    /**
     * 图片选择
     *
     * @param context  上下文
     * @param action listener
     */
    open fun showSelectDialog(context: Activity, action: (Int) -> Unit) {
        cleanDialog()
        val rootView = LayoutInflater.from(context).inflate(R.layout.layout_dialog_photo, null)
        dialog = helper?.createBaseDialog(context, R.style.AlertDialogStyle, true, rootView)
        rootView.findViewById<View>(R.id.tv_photo)
            .setOnClickListener {
                action(PHOTO_CAMERA)
                dialog?.dismiss()
            }
        rootView.findViewById<View>(R.id.tv_album)
            .setOnClickListener {
                action(PHOTO_ALBUM)
                dialog?.dismiss()
            }
        rootView.findViewById<View>(R.id.tv_cancel)
            .setOnClickListener {
                dialog?.dismiss()
            }
        helper?.adjustSizeGravity(
            dialog,
            (ScreenUtil.getScreenSize(context).x * 0.96).toInt(),
            0,
            Gravity.BOTTOM
        )
        showDialog()
    }

}